//! Server-Sent Events 处理器模块
//! 实现基于 SSE 的实时通信



use axum::{
    response::sse::{Event, KeepAlive, Sse},
    Router,
};
use axum_extra::headers::{authorization::Bearer, Authorization};
use axum_extra::TypedHeader;
use futures::Stream;
use std::{convert::Infallible, pin::Pin, sync::Arc, time::Duration};
use tokio::sync::mpsc;
use tokio_stream::{StreamExt};
use uuid::Uuid;

/// 创建 SSE 事件流
fn create_sse_stream(
    rx: tokio::sync::mpsc::UnboundedReceiver<HubResponse>
) -> Pin<Box<dyn Stream<Item = Result<Event, std::convert::Infallible>> + Send>> {
    let stream = tokio_stream::wrappers::UnboundedReceiverStream::new(rx)
        .map(|response| {
            match MessageSerializer::serialize_response(&response) {
                Ok(data) => Ok(Event::default().data(data)),
                Err(e) => {
                    tracing::error!("序列化 SSE 消息失败: {}", e);
                    Ok(Event::default().data("error: failed to serialize message"))
                }
            }
        });
    
    Box::pin(stream)
}

use super::connection::{ConnectionManagerHandle, ConnectionType, SSESender,ConnectionManager};
use super::message::{HubMessage, HubResponse, MessageSerializer, MessageType};
use crate::{
    models::token_model::TokenModel,
    services::RealtimeAuthMiddleware,
};

/// SSE 处理器
#[derive(Clone)]
pub struct SSEHandler {
    connection_manager: ConnectionManagerHandle,
    auth_middleware: RealtimeAuthMiddleware,
}

impl SSEHandler {
    pub fn new(connection_manager: ConnectionManagerHandle, auth_middleware: RealtimeAuthMiddleware) -> Self {
        Self {
            connection_manager,
            auth_middleware,
        }
    }
    
    /// 创建 SSE 路由
    pub fn create_route(&self) -> Router {
        let handler = Arc::new(self.clone());
        Router::new().route("/sse", axum::routing::get(move |auth_header: Option<TypedHeader<Authorization<Bearer>>>| {
            let handler = handler.clone();
            async move {
                let handler = Arc::clone(&handler);
                handler.handle_sse(auth_header).await
            }
        }))
    }
    
    /// 身份验证 SSE 连接
    async fn authenticate_sse_connection(
        &self, 
        auth_header: Option<TypedHeader<Authorization<Bearer>>>
    ) -> anyhow::Result<TokenModel> {
        match auth_header {
            Some(TypedHeader(Authorization(bearer))) => {
                // 构建Authorization头
                let mut headers = axum::http::HeaderMap::new();
                headers.insert(
                    "Authorization", 
                    format!("Bearer {}", bearer.token()).parse().unwrap()
                );
                
                // 使用身份验证中间件验证Token
                self.auth_middleware.authenticate_sse(&headers).await
            }
            None => Err(anyhow::anyhow!("缺少Authorization头")),
        }
    }
    
    /// 处理 SSE 连接
    pub async fn handle_sse(self: Arc<Self>, auth_header: Option<TypedHeader<Authorization<Bearer>>>) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
        // 身份验证
        let token_model = match self.as_ref().authenticate_sse_connection(auth_header).await {
            Ok(token) => token,
            Err(e) => {
                tracing::error!("SSE 连接身份验证失败: {}", e);
                // 返回错误事件流，使用相同的流类型
                let (tx, rx) = mpsc::unbounded_channel();
                let _ = tx.send(HubResponse::error(None, format!("身份验证失败: {}", e)));
                
                let stream = create_sse_stream(rx);
                
                return Sse::new(stream).keep_alive(
                    KeepAlive::new()
                        .interval(Duration::from_secs(15))
                        .text("keep-alive"),
                );
            }
        };
        
        // 创建消息通道
        let (tx, rx) = mpsc::unbounded_channel();
        
        // 创建连接发送器
        let connection_id = Uuid::new_v4();
        let sender = SSESender {
            connection_id,
            sender: tx.clone(),
        };
        
        // 注册连接（包含身份验证信息）
        let connection_id = self.connection_manager
            .add_connection_with_token(sender, ConnectionType::SSE, Some(token_model.clone()))
            .await;
        
        tracing::info!("SSE 连接建立: {} (用户: {})", connection_id, token_model.user_id);
        
        // 发送连接确认消息
        let connect_response = HubResponse::success(
            None,
            serde_json::json!({
                "connectionId": connection_id.to_string(),
                "protocol": "sse",
                "version": 1
            })
        );
        
        let _ = tx.send(connect_response);
        
        // 创建 SSE 流
        let stream = create_sse_stream(rx);
        
        // 设置 SSE 配置
        Sse::new(stream).keep_alive(
            KeepAlive::new()
                .interval(Duration::from_secs(15))
                .text("keep-alive"),
        )
    }
    
    /// 处理 SSE 消息（SSE 通常只用于接收，发送通过 HTTP POST）
    pub async fn handle_sse_message(
        &self,
        connection_id: Uuid,
        message: String,
    ) -> anyhow::Result<()> {
        // 更新连接活动时间
        self.connection_manager
            .update_connection_activity(connection_id)
            .await?;
        
        // 解析消息
        match MessageSerializer::parse_hub_message(&message) {
            Ok(hub_message) => {
                // 处理消息（SSE 通常只处理简单消息）
                match hub_message.message_type {
                    MessageType::Ping => {
                        // 响应 Ping 消息
                        let response = HubResponse::success(hub_message.invocation_id, serde_json::Value::Null);
                        self.connection_manager
                            .send_to_connection(connection_id, response)
                            .await?;
                    }
                    _ => {
                        tracing::warn!("SSE 不支持的消息类型: {:?}", hub_message.message_type);
                    }
                }
            }
            Err(e) => {
                tracing::error!("解析 SSE 消息失败: {}", e);
                
                // 发送错误响应
                let error_response = HubResponse::error(
                    None,
                    format!("消息格式错误: {}", e)
                );
                
                self.connection_manager
                    .send_to_connection(connection_id, error_response)
                    .await?;
            }
        }
        
        Ok(())
    }
}



/// SSE 消息发送端点
#[derive(Clone)]
pub struct SSEMessageEndpoint {
    connection_manager: ConnectionManagerHandle,
}

impl SSEMessageEndpoint {
    pub fn new(connection_manager: ConnectionManagerHandle) -> Self {
        Self {
            connection_manager,
        }
    }
    
    /// 创建消息发送路由
    pub fn message_route(self) -> Router {
        Router::new()
            .route("/sse/message", axum::routing::post(move |body: String| async move {
                self.handle_message_post(body).await
            }))
    }
    
    /// 处理 SSE 消息 POST 请求
    pub async fn handle_message_post(&self, body: String) -> axum::response::Json<serde_json::Value> {
        // 解析消息
        match MessageSerializer::parse_hub_message(&body) {
            Ok(hub_message) => {
                // 处理消息
                match self.process_sse_message(hub_message).await {
                    Ok(response) => axum::response::Json(response),
                    Err(e) => axum::response::Json(serde_json::json!({
                        "success": false,
                        "error": e.to_string()
                    })),
                }
            }
            Err(e) => {
                axum::response::Json(serde_json::json!({
                    "success": false,
                    "error": format!("消息格式错误: {}", e)
                }))
            }
        }
    }
    
    /// 处理 SSE 消息
    async fn process_sse_message(&self, message: HubMessage) -> anyhow::Result<serde_json::Value> {
        match message.message_type {
            MessageType::Invocation => {
                if let Some(target) = &message.target {
                    let arguments = message.arguments.unwrap_or_default();
                    
                    match target.as_str() {
                        "TokenAuth" => {
                            // TODO: 实现 Token 认证逻辑
                            Ok(serde_json::json!({
                                "success": true,
                                "message": "认证成功"
                            }))
                        }
                        "BroadcastMessage" => {
                            // 广播消息
                            if let Some(data) = arguments.get(0) {
                                let broadcast_response = HubResponse::success(
                                    None,
                                    data.clone()
                                );
                                
                                self.connection_manager.broadcast(broadcast_response).await;
                                
                                Ok(serde_json::json!({
                                    "success": true,
                                    "message": "消息已广播"
                                }))
                            } else {
                                Err(anyhow::anyhow!("缺少广播数据"))
                            }
                        }
                        _ => {
                            Err(anyhow::anyhow!("未知方法: {}", target))
                        }
                    }
                } else {
                    Err(anyhow::anyhow!("缺少目标方法"))
                }
            }
            _ => {
                Err(anyhow::anyhow!("SSE 不支持的消息类型"))
            }
        }
    }
}



#[cfg(test)]
mod tests {
    use super::*;
    use crate::services::{AuthConfig, AuthService, AuthServiceHandle, RealtimeAuthMiddleware};
    
    #[tokio::test]
    async fn test_sse_handler_creation() {
        let manager = ConnectionManager::new(10);
        let handle = ConnectionManagerHandle::new(manager);
        
        let auth_config = AuthConfig::default();
        let auth_service = AuthService::new(auth_config).unwrap();
        let auth_service_handle = AuthServiceHandle::new(auth_service);
        let auth_middleware = RealtimeAuthMiddleware::new(auth_service_handle);
        
        let handler = SSEHandler::new(handle, auth_middleware);
        
        // 测试路由创建成功 - 如果创建过程中没有panic，说明路由创建成功
        let route = handler.create_route();
        
        // 验证路由对象不为空（通过类型检查）
        assert!(std::mem::size_of_val(&route) > 0, "路由对象应该被正确创建");
        
        // 验证路由处理器类型正确
        tracing::info!("SSE 处理器路由创建成功");
    }
    
    #[tokio::test]
    async fn test_sse_endpoint_creation() {
        let manager = ConnectionManager::new(10);
        let handle = ConnectionManagerHandle::new(manager);
        let endpoint = SSEMessageEndpoint::new(handle);
        
        // 测试消息端点路由创建成功 - 如果创建过程中没有panic，说明路由创建成功
        let route = endpoint.message_route();
        
        // 验证路由对象不为空（通过类型检查）
        assert!(std::mem::size_of_val(&route) > 0, "消息端点路由对象应该被正确创建");
        
        // 验证路由处理器类型正确
        tracing::info!("SSE 消息端点路由创建成功");
    }
}